package br.edu.unicentro.mymib.entity;

import java.util.ArrayList;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.JoinColumn;
import javax.persistence.MappedSuperclass;
import javax.persistence.NoResultException;
import javax.persistence.OneToMany;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;

import org.hibernate.annotations.Cascade;

import br.edu.unicentro.mymib.base.EMFactory;

@Entity
@DiscriminatorValue("Usuario")
@MappedSuperclass
public final class Usuario extends Pessoa {

	@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
	@OneToMany(cascade = { CascadeType.ALL })
	@JoinColumn(name = "usuarioId")
	private List<Post> posts;

	@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
	@OneToMany(cascade = { CascadeType.ALL })
	@JoinColumn(name = "usuarioId")
	private List<Comentario> comentarios;

	@Column
	private boolean bloqueado;

	public Usuario() {
		posts = new ArrayList<Post>();
		bloqueado = false;
	}

	public static Usuario buscarPorEmail(String email) {
		EntityManager em = EMFactory.getManager();
		Query query = em.createNamedQuery("pessoa.findByEmail");
		query.setParameter("email", email);
		try {
			return (Usuario) query.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	public void adicionarPost(Post post) throws Exception {
		posts.add(post);
	}

	public void excluirPost(Post post) throws Exception {
		Post postRemover = null;
		for (Post p : posts) {
			if (p.getId().longValue() == post.getId().longValue()) {
				postRemover = p;
				break;
			}
		}
		posts.remove(postRemover);
	}

	public List<Post> getPosts() {
		return posts;
	}

	public static Usuario recuperarUsuarioLogado() {
		Usuario u = null;

		HttpServletRequest request = ((HttpServletRequest) FacesContext
				.getCurrentInstance().getExternalContext().getRequest());

		if (request.isUserInRole("GRANTED")) {
			String userName = request.getUserPrincipal().getName();
			u = Usuario.buscarPorEmail(userName);
		}

		return u;
	}

	public static Usuario recuperarAdmin() {
		Usuario u = null;

		HttpServletRequest request = ((HttpServletRequest) FacesContext
				.getCurrentInstance().getExternalContext().getRequest());

		if (request.isUserInRole("ADMIN")) {
			String userName = request.getUserPrincipal().getName();
			u = Usuario.buscarPorEmail(userName);
		}

		return u;
	}

	public void clearPosts() {
		posts = new ArrayList<Post>();
	}

	public boolean isBloqueado() {
		return bloqueado;
	}

	public void setBloqueado(boolean bloqueado) {
		this.bloqueado = bloqueado;
	}

}
